<script setup lang='ts'>
import { BindMobile, LoginByQQ } from '@/apis/user';
import { RuleMobile, RulesCode } from '@/utils/rules';
import { showSuccessToast } from 'vant';
import { onMounted, ref } from 'vue';
import { useMobileCode } from '@/composables/useMobileCode'
import type { User } from '@/types/user';
import { useUserStore } from '@/stores';
import { useRouter } from 'vue-router';

const store = useUserStore()
const router = useRouter()
const openId = ref('')
const mobile = ref('')
const code = ref('')

const isNeedBind = ref(false)
onMounted(() => {
  if (QC.Login.check()) {
    QC.Login.getMe((id) => {
      openId.value = id
      LoginByQQ(id)
        .then((res) => {
          // QQ登录过绑定手机号了就直接走这里
          LoginSuccess(res.data)
        })
        .catch(() => {
          isNeedBind.value = true
        })
    })
  }
})
//发送验证码
const { sendCode, time, form } = useMobileCode(mobile, 'bindMobile')

//登入成功
const LoginSuccess = (data: User) => {
  store.setUser(data)
  router.push('/user')
  showSuccessToast('登陆成功')
}
const submitBind = async () => {
  const res = await BindMobile({
    mobile: mobile.value,
    code: code.value,
    openId: openId.value
  })
  LoginSuccess(res.data)
}

</script>

<template>

  <div class="login-page" v-if="isNeedBind">
    <cp-nav-bar></cp-nav-bar>
    <div class="login-head">
      <h3>手机绑定</h3>
    </div>
    <van-form autocomplete="off" @submit="submitBind" ref="form">
      <van-field name="mobile" v-model="mobile" :rules="RuleMobile" placeholder="请输入手机号"></van-field>
      <van-field name="code" v-model="code" :rules="RulesCode" placeholder="请输入验证码">
        <template #button>
          <span class="btn-send" @click="sendCode" :class="{ active: time }">{{ time > 0 ? `${time}后再发送` : '发送验证码'
            }}</span>
        </template>
      </van-field>
      <div class="cp-cell">
        <van-button block round type="primary" native-type="submit"> 立即绑定 </van-button>
      </div>
    </van-form>
  </div>

</template>
<style lang="scss" scoped>
@import '@/styles/login.scss';
</style>